package com.yt.brand.service.impl;

import com.yt.brand.data.HireCarBrandMapper;
import com.yt.brand.entity.HireCarBrand;
import com.yt.brand.service.IHireCarBrandService;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.soul.commons.cn.PinYinTool;
import org.soul.commons.log.Log;
import org.soul.commons.log.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Random;


/**
 * @author shadow
 */
@Service
public class HireCarBrandService implements IHireCarBrandService {

    private static final Log LOG = LogFactory.getLog(HireCarBrandService.class);
    private static final int RANDOM_NUM = new Random().nextInt(500) + 1;

    @Autowired
    private HireCarBrandMapper hireCarBrandMapper;

    /**
     * 添加品牌
     */
    @Override
    public void addBrand() throws Exception {

            LOG.info("添加品牌流程开始");
            String url="https://car.autohome.com.cn/AsLeftMenu/As_LeftListNew.ashx?typeId=1%20";
            Document doc= Jsoup.connect(url).timeout(600000).get();
            Elements li = doc.getElementsByTag("li");

            for (Element element : li) {
                String id = element.attr("id").substring(1);
                String text = element.text();
                String newText = text.substring(0, text.indexOf("("));
                String initial = PinYinTool.getPinYinHeadChars(element.text()).toUpperCase().substring(0, 1);
                //添加一级品牌
                HireCarBrand hireCarBrand = new HireCarBrand();
                hireCarBrand.setInitial(initial);
                hireCarBrand.setName(newText);
                hireCarBrand.setBuiltIn(true);
                hireCarBrand.setParentId(0);
                hireCarBrand.setLevel("1");
                hireCarBrand.setPinyin(PinYinTool.getPinYin(newText));
                //根据品牌信息获取品牌id
                Integer brandById = hireCarBrandMapper.getBrandById(hireCarBrand);
                Integer parentId = null;
                if (brandById == null){
                    hireCarBrandMapper.add(hireCarBrand);
                    parentId = hireCarBrand.getId();
                } else {
                    parentId = brandById;
                }

                //添加二级品牌
                getTwoBrand(id, parentId);
            }
        LOG.info("添加品牌流程结束");
    }

    /**
     * 添加二级品牌
     * @param id
     * @param parentId
     * @throws IOException
     */
    private void getTwoBrand(String id, Integer parentId) throws Exception {
        String url2 = "https://car.autohome.com.cn/AsLeftMenu/As_LeftListNew.ashx?typeId=1%20&brandId="+ id +"%20&fctId=0%20&seriesId=0";
        LOG.info("进入二级品牌添加流程, 目标URL地址: {0}", url2);
        Document doc2= Jsoup.connect(url2).timeout(600000).get();
        Elements li2 = doc2.getElementsByTag("dd");
        //二级页面
        for (Element element2 : li2) {
            String attr = element2.getElementsByTag("a").attr("href");
            //处理数据
            String text2 = element2.text();
            String newText2 = text2.substring(0, text2.indexOf("("));
            String initial2 = PinYinTool.getPinYinHeadChars(element2.text()).toUpperCase().substring(0, 1);
            HireCarBrand hireCarBrand = new HireCarBrand();
            hireCarBrand.setInitial(initial2);
            hireCarBrand.setName(newText2);
            hireCarBrand.setBuiltIn(true);
            hireCarBrand.setLevel("2");
            hireCarBrand.setPinyin(PinYinTool.getPinYin(newText2));
            hireCarBrand.setParentId(parentId);
            //根据品牌信息获取品牌id
            Integer brandById = hireCarBrandMapper.getBrandById(hireCarBrand);
            Integer parentId2 = null;
            if (brandById == null){
                hireCarBrandMapper.add(hireCarBrand);
                parentId2 = hireCarBrand.getId();
            } else {
                parentId2 = brandById;
            }

            //添加三级品牌
             getThirdBrand(attr, parentId2);
        }
        LOG.info("完成二级品牌添加流程, 目标URL地址: {0}",  url2);
    }

    /**
     * 添加三级品牌
     * @param attr
     * @param parentId
     * @throws IOException
     */
    private void getThirdBrand(String attr, Integer parentId) throws Exception {
        String url3 = "https://car.autohome.com.cn"+ attr;
        LOG.info("进入三级品牌添加流程, 目标URL地址: {0}", url3);

        Document doc3 = Jsoup.connect(url3)
                .ignoreContentType(true).maxBodySize(0).followRedirects(false)
                .method(Connection.Method.POST).timeout(600000)
                .header("Content-Type","application/json")
                .get();

        Elements li3 = doc3.getElementsByClass("interval01-list-cars-infor");
            //三级页面
            for (Element element3 : li3) {
                String text3 = element3.text();
                String text4= text3.substring(0, text3.indexOf("款"));

                HireCarBrand hireCarBrand = new HireCarBrand();
                hireCarBrand.setName(text3);
                hireCarBrand.setParentId(parentId);
                hireCarBrand.setYears(text4);
                hireCarBrand.setBuiltIn(true);
                hireCarBrand.setLevel("3");

                //根据品牌信息获取品牌id
                Integer brandById = hireCarBrandMapper.getBrandById(hireCarBrand);
                if (brandById == null){
                    hireCarBrandMapper.add(hireCarBrand);
                }

                //睡眠时间设定(防止ip被禁)
                Thread.sleep(RANDOM_NUM);
            }
        LOG.info("完成三级品牌添加流程, 目标URL地址: {0}",  url3);
    }

}
